<?php
/**
 * Copyright 2011 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

require_once "Base_facebook.php";

/**
 * Extends the BaseFacebook class with the intent of using
 * PHP sessions to store user ids and access tokens.
 */
class Facebook extends BaseFacebook
{	
	private static  $instance;
	public static  $me;
	public static  $friends;
	
 
	
 	// Produção 
  	const PERMISSOES="user_photos,publish_stream, friends_photos ";
	const CANVAS_URL='';
	const REDIRECT_URI='http://apps.facebook.com/BrasileiraoSocial';
	const BASE_URL="http://apps.facebook.com/BrasileiraoSocial";
	const API_ID='318370724901195';					  
	const SECRET='4305f05d5069f2631312fa49e88dddb5';
		
  /**
   * Identical to the parent constructor, except that
   * we start a PHP session to store the user ID and
   * access token if during the course of execution
   * we discover them.
   *
   * @param Array $config the application configuration.
   * @see BaseFacebook::__construct in facebook.php
   */
  public function __construct($config) {  
  if (!session_id()) {
      session_start();
    }  
    parent::__construct($config);
  }
  
   
  

  public static function getInstance(){  	
  	  	  	
  		if((isset(self::$instance) && self::$instance instanceof Facebook)){ 	  			   		  		
  			return self::$instance;
  		}else{ 	  				
	  		self::$instance = new Facebook(array(
		      'appId'  => self::API_ID,
		      'secret' => self::SECRET,
		      'fileUpload' => true
		    ));			    
  		  	$user = self::$instance->getUser(); 		  	  		  	  	
			if (!$user) { 	        
				Facebook::redirectToken();
				exit;        
			}		    	
		    self::$me=self::$instance->api('/me');		    	
			return self::$instance;			 			    
  		}
  } 

 
  /*    
  public static function getInstance(){  	
  	  	
  			
	  	 if((isset(self::$instance) && self::$instance instanceof Facebook)){
	  		return self::$instance;
	  		  			  			
	  	}else if( isset($_GET['code']) || !isset($_SESSION['instance'])){
	  		
	  		self::$instance = new Facebook(array(
		      'appId'  => self::API_ID,
		      'secret' => self::SECRET,
		      'fileUpload' => true
		    ));			   
		    
	  	  	$user = self::$instance->getUser();  		  	 	  	
			if (!$user) { 	        
				Facebook::redirectToken();
				exit;        
			}		    	
			
		    self::$me = self::$instance->api('/me');
		    self::$friends = self::$instance->api("me/friends");
		    
		    // Valida as permições do usuário, caso não tenha permições adeguadas redirecione para o pedido de permição
		    self::$instance->validaPermissoes();		    
		     
		    $_SESSION['me'] = serialize(self::$me);
		    $_SESSION['instance'] = serialize(self::$instance);
		    $_SESSION['friends'] = serialize(self::$friends);
		    
			return self::$instance;			 			    
	  		
	  	}else if(isset($_SESSION['instance'])){			
	  		
	  		self::$me = unserialize($_SESSION['me']);
		    self::$instance = unserialize($_SESSION['instance']);
		    self::$friends = unserialize($_SESSION['friends']);		    
		    return self::$instance;		    
	  	}
  }  
    */
   
  public static function getInstanceCron(){  	
  	  	  	
  		if((isset(self::$instance) && self::$instance instanceof Facebook)){ 	  			   		  		
  			return self::$instance;
  		}else{ 	  				
	  		self::$instance = new Facebook(array(
		      'appId'  => self::API_ID,
		      'secret' => self::SECRET,
		      'fileUpload' => true
		    ));		      		       	
			return self::$instance;			 			    
  		}
  }

  
  public static function usuarioJaAceitou(){  	
  		 	  				
  		$objFacebook = new Facebook(array(
	      'appId'  => self::API_ID,
	      'secret' => self::SECRET,
	      'fileUpload' => true
	    ));		    	    
  	  	$user = $objFacebook->getUser(); 
  	  	 		  	   
		if (!$user) {						
			// usuário não aceitou a aplicação ainda	        
			return false;
		}else // usuário já aceitou o aplicativo
	    	return true;	    
  }  

	public function validaPermissoes(){
		
		if(isset($_SESSION['permitido']))
			return true;			

		$perm = $this->getPersistentData("permissions");	
		if(!$perm){			  	  	
	  		$perm=$this->api('/me/permissions');  		  	 	  	  	
	  		$this->setPersistentData("permissions", $perm);
		}
	  	foreach(explode(",",self::PERMISSOES) as $permissao){		
	  		
	  		if(!isset($perm['data'][0][$permissao])){
				Facebook::redirectToken();
				exit;  
	  		}  		
	  	} 
	  	
	  	$_SESSION['permitido'] = "ok";		  	
  		return true;
  }
  
  public static function redirectToken(){   	
    	
    	echo "<script type='text/javascript'>window.open('".Facebook::urlPermission()."', '_parent', '');</script>";
  		exit;   		
  }  
  
  public static function urlPermission(){    	
    	return "https://www.facebook.com/dialog/oauth?client_id=".self::API_ID."&redirect_uri=".self::REDIRECT_URI."&scope=".self::PERMISSOES;  		   		
  }  
  
  
  
  public function getMe(){  		
		return self::$me;
  }
  
  public function getFriends(){  	
		return self::$friends;
  }  
  
  
  protected static $kSupportedKeys =
    array('state', 'code', 'access_token', 'user_id','permissions');

  /**
   * Provides the implementations of the inherited abstract
   * methods.  The implementation uses PHP sessions to maintain
   * a store for authorization codes, user ids, CSRF states, and
   * access tokens.
   */
  protected function setPersistentData($key, $value) {
    if (!in_array($key, self::$kSupportedKeys)) {
      self::errorLog('Unsupported key passed to setPersistentData.');
      return;
    }

    $session_var_name = $this->constructSessionVariableName($key);
    $_SESSION[$session_var_name] = $value;
  }

  protected function getPersistentData($key, $default = false) {
    if (!in_array($key, self::$kSupportedKeys)) {
      self::errorLog('Unsupported key passed to getPersistentData.');
      return $default;
    }

    $session_var_name = $this->constructSessionVariableName($key);
    return isset($_SESSION[$session_var_name]) ?
      $_SESSION[$session_var_name] : $default;
  }

  protected function clearPersistentData($key) {
    if (!in_array($key, self::$kSupportedKeys)) {
      self::errorLog('Unsupported key passed to clearPersistentData.');
      return;
    }

    $session_var_name = $this->constructSessionVariableName($key);
    unset($_SESSION[$session_var_name]);
  }

  protected function clearAllPersistentData() {
    foreach (self::$kSupportedKeys as $key) {
      $this->clearPersistentData($key);
    }
  }

  protected function constructSessionVariableName($key) {
    return implode('_', array('fb',
                              $this->getAppId(),
                              $key));
  }
}
